package com.simpleplayer.contentview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

@SuppressLint("ViewConstructor")
class ContentTextureView extends TextureView
        implements android.view.TextureView.SurfaceTextureListener, ContentView {

    private final SurfaceListener mSurfaceListener;
    private Surface mSurface;

    private int mContentWidth = 0;
    private int mContentHeight = 0;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public ContentTextureView(@NonNull Context context, SurfaceListener listener) {
        super(context);
        this.mSurfaceListener = listener;

        if (listener != null) {
            setSurfaceTextureListener(this);
        }

        setAlpha(1);
        setRotation(0);
    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = 1;
        int height = 1;
        if (mContentWidth > 0 && mContentHeight > 0) {
            width = getDefaultSize(mContentWidth, widthMeasureSpec);
            height = getDefaultSize(mContentHeight, heightMeasureSpec);
            if (mContentWidth * height  > width * mContentHeight) {
                height = width * mContentHeight / mContentWidth;
            } else if (mContentWidth * height  < width * mContentHeight) {
                width = height * mContentWidth / mContentHeight;
            }
        }
        setMeasuredDimension(width, height);
    }

    @Override
    public void onContentSizeChanged(int width, int height) {
        if (width == 0 || height == 0)
            return;
        if (mContentWidth != width || mContentHeight != height) {
            mContentWidth = width;
            mContentHeight = height;
            if (getSurfaceTexture() != null) {
                getSurfaceTexture().setDefaultBufferSize(width, height);
            }
            requestLayout();
        }
    }

    @NonNull
    @Override
    public TextureView getView() {
        return this;
    }

    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        mSurface = new Surface(surface);
        mSurfaceListener.onSurfaceCreate(mSurface);
    }

    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
    }

    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
        mSurfaceListener.onSurfaceDestroy(mSurface);
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
    }
}
